using MediatR;
using B.S.XZYData.Api.Wrter.Application.Command.Route;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using SqlSugar;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Route
{
    public class AddRouteHandler : IRequestHandler<AddRouteCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RouteModel> _routeRepository;

        public AddRouteHandler(IBaseRepository<RouteModel> routeRepository)
        {
            _routeRepository = routeRepository;
        }

        public async Task<ApiResult<int>> Handle(AddRouteCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            
            try
            {
                // 检查工艺路线编号是否已存在
                var exists = await _routeRepository.GetAll()
                    .Where(x => x.Code == request.Code)
                    .AnyAsync();
                if (exists)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "工艺路线编号已存在";
                    return res;
                }

                // 创建工艺路线实体
                var route = new RouteModel
                {
                    Code = request.Code,
                    Name = request.Name,
                    Approved = request.EnableApproval ? (byte)1 : (byte)0,
                    Remark = request.Remark,
                    CreateBy = request.OperateBy,
                    CreateTime = DateTime.Now,
                    UpdateBy = request.OperateBy,
                    UpdateTime = DateTime.Now
                };

                // 保存工艺路线主表，获取返回的ID
                var routeId = await _routeRepository.CreateAsync(route);
                if (routeId <= 0)
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "添加工艺路线失败";
                    return res;
                }

                res.Code = ApiEnum.Success;
                res.Msg = "新增工艺路线成功";
                res.Data = routeId;
                return res;
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"新增工艺路线异常：{ex.Message}";
                return res;
            }
        }
    }
} 